<template>
  <div class="view-main">
    <!-- <LeftPop>
      <FoldListData  @handle = "operateFeatureLayer"/>
    </LeftPop> -->
    <div id="viewDiv"></div>
    <div id="infoDiv" class="esri-widget">
      <Legend :legendList="legendList"></Legend>
    </div>
    <tool ref="topTools" @handle="operateFeatureLayer" />
  </div>
  <el-dialog
    v-model="dialogNormalVisible"
    top="0"
    padding="0"
    destroy-on-close
    fullscreen="true"
    center
    @opened="selectType('classType2', 2, 12)"
  >
    <div style="overflow: hidden">
      <el-row type="flex" :gutter="10" justify="center">
        <el-col :span="20">&nbsp;</el-col>
        <el-col :span="4"
          ><div class="grid-content bg-purple">
            <el-button-group>
              <el-button
                :type="classType2"
                @click="selectType('classType2', 2, 12)"
                >二分屏</el-button
              >
              <el-button
                :type="classType4"
                @click="selectType('classType4', 4, 12)"
                >四分屏</el-button
              >
            </el-button-group>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="el-row">
        <el-col
          v-for="(n, index) in screenNum"
          :key="index"
          :xs="24"
          :sm="24"
          :md="cloNum"
          :lg="cloNum"
          :xl="cloNum"
          :class="screenClass"
        >
          <div class="player-wrapper" element-loading-background="#FFF">
            <div class="screen-main">
              <div class="screen-wrapper" :style="screenClass">
                <div class="screen-map" :id="`screen${n}`"></div>
                <el-select
                  v-model="value"
                  placeholder="Select"
                  class="screen-select"
                  @change="addFeatureMap(value, n)"
                >
                  <el-option
                    v-for="item in operateFeatureLayerList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
  <el-dialog
    v-model="dialogRollerVisible"
    top="0"
    padding="0"
    destroy-on-close
    fullscreen="true"
    center
    @opened="rollerInit()"
  >
    <div style="overflow: hidden">
      <div class="player-wrapper" element-loading-background="#FFF">
        <div class="screen-main">
          <div
            class="screen-wrapper"
            style="padding-bottom: 50%; position: relative; margin: 0px auto"
          >
            <div class="screen-map" id="screenRoller"></div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import {
  defineComponent,
  onMounted,
  PropType,
  reactive,
  ref,
  nextTick,
} from "vue";
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import Extent from "@arcgis/core/geometry/Extent";
import TileLayer from "@arcgis/core/layers/TileLayer";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer";
import Swipe from "@arcgis/core/widgets/Swipe";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import UniqueValueRenderer from "@arcgis/core/renderers/UniqueValueRenderer";
import SimpleLineSymbol from "@arcgis/core/symbols/SimpleFillSymbol";
import Basemap from "@arcgis/core/Basemap";
import Expand from "@arcgis/core/widgets/Expand";

import LeftPop from "@/components/LeftPop/LeftPop.vue";
import Legend from "@/components/legend/Legend.vue";
import Tool from "@/components/tool/Tool.vue";

import axios from "../../utils/http";
import FoldListData from "./basicFolder/foldList.vue";
import Bus from "./func/Bus";
import mapAxios from "axios";

import { config } from "./config";

export default defineComponent({
  props: {
    basemap: {
      type: Object as PropType<null | "">,
    },
  },
  data() {
    return {};
  },
  components: {
    LeftPop,
    Legend,
    FoldListData,
    Tool,
  },
  setup(props, ctx) {
    let basemap = new Basemap({
      baseLayers: [
        new TileLayer({
          url: config.baseMapUrl,
          title: "Basemap",
        }),
      ],
      title: "basemap",
      id: "basemap",
    });

    const map = new Map({ basemap: basemap });
    let view: any = null;
    let legendList = ref([]);
    let rollerView: any = null;
    let expand: any = null;
    let topTools: any = ref(null);
    let dialogNormalVisible = ref(false);
    let dialogRollerVisible = ref(false);
    let screenNum: any = ref(2);
    let cloNum: any = ref(12);
    let screenClass: any = ref(
      "padding-bottom: 100%; position: relative; margin: 0px auto;"
    );
    let classType2: any = ref("primary");
    let classType4: any = ref("");

    // 要素图层集合、属性查询
    let FeatureLayerList = [];
    // 所有地图集合
    let operateFeatureLayerList = [];

    // screen中的视图集合
    let screenViewList = [];
    let screenMapList = [];
    const init = () => {
      view = new MapView({
        container: "viewDiv",
        map: map,
        center: [86.6, 40.7],
        zoom: 10,
      });

      view.extent = new Extent({
        xmin: -8649827.836014,
        ymin: 5327540.8426351305,
        xmax: -8630753.997105986,
        ymax: 5352890.850468009,
        spatialReference: {
          wkid: 102100,
        },
      });

      expand = new Expand({
        content: document.getElementById("infoDiv"),
        view: view,
        expanded: false,
      });

      // 获取所有的图层列表
      // axios.get('/map/layerList/' + addOrRemoveLayer.id)
      //     .then((res) => {
      //          operateFeatureLayerList.push(operateFeatureLayer);
      //     }).catch((err) => {
      //         console.log('err: ', err)
      //     });
    };
    const operateFeatureLayer = (operateFeatureLayer: any) => {
      switch (operateFeatureLayer.type) {
        case "addOrRemoveLayer":
          operateFeatureLayerList.push(operateFeatureLayer);
          if (map.layers.find((layer) => layer.id == operateFeatureLayer.id)) {
            map.layers.find(
              (layer) => layer.id == operateFeatureLayer.id
            ).visible = operateFeatureLayer.status;
          } else {
            if (operateFeatureLayer.mapType == "0") {
              const transportationLayer = new TileLayer({
                id: operateFeatureLayer.id,
                url: operateFeatureLayer.url,
                legendEnabled: false,
                visible: true,
              });
              map.add(transportationLayer);
            }
            if (operateFeatureLayer.mapType == "1") {
              const mapImageLayer = new MapImageLayer({
                id: operateFeatureLayer.id,
                url: operateFeatureLayer.url,
                legendEnabled: false,
                visible: true,
                outFields: ["*"],
              });
              map.add(mapImageLayer);
              setTimeout(() => {
                // 添加要素图层
                mapImageLayer.allSublayers.forEach((sub) => {
                  const featureLayer = new FeatureLayer({
                    id: sub.id,
                    url: sub.url,
                    legendEnabled: false,
                    visible: true,
                    outFields: ["*"],
                  });
                  map.add(featureLayer);
                  FeatureLayerList.push(featureLayer);
                });
              }, 1000);
            }
          }
          break;
        case "opacityChange":
          if (map.layers.find((layer) => layer.id == operateFeatureLayer.id)) {
            map.layers.find(
              (layer) => layer.id == operateFeatureLayer.id
            ).opacity = operateFeatureLayer.opacity;
          }
          break;
        case "legendLayerAdd":
          mapAxios
            .get(operateFeatureLayer.url + "/legend?f=pjson")
            .then((res) => {
              if (!!res.data) {
                legendList.value.push({
                  id: operateFeatureLayer.id,
                  name: operateFeatureLayer.name,
                  legends: res.data.layers,
                });

                console.log(legendList);
              }
            })
            .catch((err) => {
              console.log("err: ", err);
            });
          break;
        case "fullAllLayer":
          if (map.layers.find((layer) => layer.id == operateFeatureLayer.id)) {
            view.center = [86.6, 40.7];
            view.extent = map.layers.find(
              (layer) => layer.id == operateFeatureLayer.id
            ).fullExtent;
          }
          break;
        case "collectionLayer":
          // 请求后端接口进行收藏
          axios
            .get("/users/XPoet")
            .then((res) => {})
            .catch((err) => {
              console.log("err: ", err);
            });
          break;
        case "locationHandle":
          view.center = [operateFeatureLayer.lat, operateFeatureLayer.lng];
          break;
        case "mapFullView":
          if (map.basemap && map.basemap.baseLayers.getItemAt(0)) {
            const extent = map.basemap.baseLayers.getItemAt(0).fullExtent;
            view.extent = extent;
          }
          break;
        case "attributeQuery":
          if (FeatureLayerList) {
            view.on("pointer-move", function (evt) {
              var screenPoint = { x: evt.x, y: evt.y };
              view.hitTest(screenPoint).then(function (response) {
                getGraphics(response, FeatureLayerList);
              });
            });

            view.on("click", (event) => {
              queryFeatures(event, FeatureLayerList);
            });
          }
          break;
        case "screenView":
          if (operateFeatureLayer.command == "normal") {
            dialogNormalVisible.value = true;
          }
          if (operateFeatureLayer.command == "roller") {
            dialogRollerVisible.value = true;
          }
          break;
      }
    };
    const queryFeatures = (screenPoint: any, layer: any) => {
      const point = view.toMap(screenPoint);
      layer.forEach((item) => {
        item
          .queryFeatures({
            geometry: point,
            spatialRelationship: "intersects",
            returnGeometry: false,
            returnQueryGeometry: true,
            outFields: ["*"],
          })
          .then((featureSet) => {
            // open popup of query result
            console.log(featureSet);
            view.popup.open({
              location: point,
              features: featureSet.features,
              featureMenuOpen: true,
            });
          });
      });
    };
    const selectType = (type, num, clo) => {
      screenNum.value = num;
      cloNum.value = clo;
      if (type === "classType2") {
        classType2.value = "primary";
        classType4.value = "";
        screenClass.value =
          "padding-bottom: 100%; position: relative; margin: 0px auto;";
      } else if (type === "classType4") {
        classType2.value = "";
        classType4.value = "primary";
        screenClass.value =
          "padding-bottom: 50%; position: relative; margin: 0px auto;";
      }
      nextTick(() => {
        for (let i = 1; i < num + 1; i++) {
          screenMapList.push(new Map());
          // 添加地图到分屏中
          let screenView = new MapView({
            container: "screen" + i,
            map: screenMapList[i - 1],
            center: [-74, 40.73],
            zoom: 10,
          });
          screenViewList.push(screenView);
        }
        screenViewList.forEach(function (screenView) {
          //定义一个范围变量
          var fullextent = null;
          //设置鼠标滚轮事件
          screenView.on("mouse-wheel", function (e) {
            //延迟获取范围的函数
            window.setTimeout(function () {
              //获取操作图层的范围
              fullextent = screenView.extent;
              //遍历所有视图来设置这个范围
              screenViewList.forEach(function (nview) {
                nview.extent = fullextent;
              });
            }, 1000);
          });
          //设置鼠标拖拽事件
          screenView.on("drag", function (e) {
            //获取操作图层的范围
            fullextent = screenView.extent;
            //遍历所有视图来设置这个范围
            screenViewList.forEach(function (nview) {
              nview.extent = fullextent;
            });
          });
        });
      });
    };
    const rollerInit = () => {
      nextTick(() => {
        const rollerMap = new Map({ basemap: basemap });

        const transportationLayer = new TileLayer({
          url: "https://server.arcgisonline.com/arcgis/rest/services/Reference/World_Transportation/MapServer",
          id: "523767455051415552",
          legendEnabled: false,
          visible: true,
        });
        rollerMap.add(transportationLayer);
        const infrared = new TileLayer({
          url: "https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/WV03_Kilauea_20180519_ShortwaveInfrared/MapServer",
        });

        const featureLayer = new FeatureLayer({
          portalItem: {
            id: "234d2e3f6f554e0e84757662469c26d3",
          },
          legendEnabled: false,
          visible: true,
          outFields: ["*"],
        });

        rollerMap.add(featureLayer);

        rollerView = new MapView({
          container: "screenRoller",
          map: rollerMap,
          center: [-74, 40.73],
          zoom: 10,
        });

        // create a new Swipe widget
        const swipe = new Swipe({
          leadingLayers: [transportationLayer],
          trailingLayers: [],
          position: 35,
          view: rollerView,
        });

        // add the widget to the view
        rollerView.ui.add(swipe);
      });
    };
    const addFeatureMap = (value: any, index: any) => {
      let tempOperateFeatureLayer = operateFeatureLayerList.find(
        (layer) => layer.id == value
      );
      if (
        screenViewList[index - 1] &&
        screenMapList[index - 1] &&
        tempOperateFeatureLayer
      ) {
        // 移除地图
        screenMapList[index - 1].removeAll();
        if (tempOperateFeatureLayer.mapType == 0) {
          const transportationLayer = new TileLayer({
            url: tempOperateFeatureLayer.url,
            id: tempOperateFeatureLayer.id,
            legendEnabled: false,
            visible: true,
          });
          screenMapList[index - 1].add(transportationLayer);
        }
        if (tempOperateFeatureLayer.mapType == 1) {
          const featureLayer = new FeatureLayer({
            portalItem: {
              id: "234d2e3f6f554e0e84757662469c26d3",
            },
            legendEnabled: false,
            visible: true,
            outFields: ["*"],
          });
          screenMapList[index - 1].add(featureLayer);
        }
      }
    };
    const getGraphics = (response: any, featureLayerList: Array) => {
      document.getElementById("viewDiv").style.cursor = "crosshair";

      if (response.results.length > 0) {
        response.results.forEach((res, i) => {
          FeatureLayerList.forEach((item, index) => {
            const graphic = res.graphic;
            if (graphic.layer.id == item.id && item.id != "0") {
              var attributes = graphic.attributes;
              var name = attributes.Section;
              var wind = attributes.Section_Num;

              console.log(name);

              // dom.byId("info").style.visibility = "visible";
              // dom.byId("name").innerHTML = name;
              // dom.byId("category").innerHTML = "Category " + category;
              // dom.byId("wind").innerHTML = wind + " kts";

              // symbolize all line segments with the given
              // storm name with the same symbol

              var renderer = new UniqueValueRenderer({
                type: "unique-value",
                field: "REGION",
                uniqueValueInfos: [
                  {
                    value: name,
                    symbol: {
                      type: "simple-fill", // autocasts as new SimpleFillSymbol()
                      color: "red",
                    },
                  },
                ],
              });
              item.renderer = renderer;
            }
          });
        });
      }
    };
    onMounted(() => {
      init();
      // 移除放大缩小组件以及Esri Logo标志
      view.ui.remove(["attribution", "zoom"]);
      view.ui.add(topTools.value.$el, "top-right");
      // view.ui.move("zoom", "bottom-right");
      view.ui.add("infoDiv", "bottom-right");
      view.ui.add(expand, "bottom-right");

      Bus.$on("map-handle", (data: any) => {
        operateFeatureLayer(data);
      });
    });
    return {
      operateFeatureLayer,
      selectType,
      addFeatureMap,
      rollerInit,
      legendList,
      topTools,
      operateFeatureLayerList,
      dialogNormalVisible,
      dialogRollerVisible,
      screenNum,
      cloNum,
      screenClass,
      classType2,
      classType4,
    };
  },
});
</script>

<style lang="less" scoped>
.view-main {
  height: 100%;
  background: #efefef;
}

#viewDiv {
  position: absolute;
  height: 100%;
  width: 100%;
}
#infoDiv {
  background-color: white;
  padding: 10px;
  max-height: 375px;
  overflow: auto;
}
:deep(.esri-ui-corner) {
  position: absolute;
  display: block;
}
  :deep(.esri-expand) {
  margin-top: 10px;
}

:deep(.esri-expand__content--expanded) {
  width: 300px;
  box-shadow: 0 0px !important;
}

.player-wrapper {
  position: relative;
  /*padding-bottom: 8px;*/
}

.screen-main {
  position: relative;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  border: 0.1px solid #0d84ff;
}

.screen-map {
  position: absolute;
  height: 100%;
  width: 100%;
}

.screen-select {
  float: right;
  margin-top: 15px;
  margin-right: 15px;
}
</style>
